<template>
	<div class="detail" v-if="detail">
		<Header><span slot="back" @click="goback">返回</span></Header>
		<div class="detail">
			<img :src="detail.coverImg" alt="" />
			<h3>{{ detail.name }}</h3>
			<p>{{ detail.price }}元</p>
			<van-button type="primary" size="large" @click="addCart(detail._id)"
				>加入购物车</van-button
			>
		</div>
	</div>
</template>

<script>
import Header from "@/components/header";
import { reqProductDetail, reqAddCart } from "@/api/product";
import { Toast } from "vant";
Toast.setDefaultOptions({ duration: 500 });
export default {
	data() {
		return {
			detail: "",
		};
	},
	computed: {},
	watch: {},

	methods: {
		// 点击 返回 返回到首页
		goback() {
			// 返回上一个历史
			this.$router.go(-1);
		},
		// 调用商品详情接口
		async getProductDetail(id) {
			const res = await reqProductDetail(id);
			console.log(res);
			// 详情
			this.detail = res;
		},
		// 点击加入购物车按钮，调用购物车接口
		async addCart(id) {
			console.log(id);
			let data = {
				product: id,
				quantity: 1,
			};
			const res = await reqAddCart(data);
			// {code: 'success', message: '加入购物车成功！'}
			console.log(res);
			Toast(res.message);
			if (res.code == "success") {
				// 跳转到购物车页面
				this.$router.push("/cart");
			}
		},
	},
	created() {
		// 获取传递过来的id
		const id = this.$route.params.id;
		// 调用获取商品详情方法
		this.getProductDetail(id);
	},
	mounted() {},
	components: {
		Header,
	},
};
</script>
<style scoped>
.detail {
	text-align: center;
}
.detail img {
	margin-top: 20px;
	width: 200px;
	height: 200px;
}
.detail h3,
.detail p {
	line-height: 30px;
}
.detail h3 {
	font-weight: 800;
	font-size: 18px;
}
</style>
